<!--
 * @description  : 实地核查方位图-自定义描点-添加学校页面
 * @create       : 2024-7-30
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"> </theme-navbar>
    <!-- #endif -->
    <view class="m-content">
      <view class="tip">
        <view :style="{ display: 'inline-block', marginRight: '10rpx' }">拖动</view>
        <u-image width="16px" src="/static/certificate/position_picker.png" mode="widthFix"></u-image>
        <view :style="{ display: 'inline-block', marginLeft: '36rpx' }">进行描点选址</view>
      </view>
      <view :style="{ width: getContainerWidth(), height: getContainerHeight() }" id="container"></view>
      <view class="m-market">
        <u-row :gutter="6" class="row">
          <u-col :span="3">名称：</u-col>
          <u-col :span="9" class="row-value">{{ curEntityName }}</u-col>
        </u-row>
        <u-row :gutter="6" class="row">
          <u-col :span="3">位置：</u-col>
          <u-col :span="9" class="row-value">{{ getRegeocodeInfo() }}</u-col>
        </u-row>
        <u-row :gutter="6" class="row">
          <u-col :span="3">经度/纬度：</u-col>
          <u-col :span="9" class="row-value">{{ newPosition.lng }}/{{ newPosition.lat }}</u-col>
        </u-row>
        <u-row :gutter="3" class="row">
          <u-col :span="3">是否出入口：</u-col>
          <u-col :span="3" class="row-value">
            <u-switch v-model="isGate"></u-switch>
          </u-col>
          <u-col :span="3">是否中小学：</u-col>
          <u-col :span="3" class="row-value">
            <u-switch v-model="isSchool"></u-switch>
          </u-col>
        </u-row>
        <u-row class="row">
          <u-col :span="12" class="row-button">
            <u-button type="primary" @click="submitEntity">
              确定
            </u-button>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script>
import { AMapMixin } from "@/common/AMapMixin.js";
import certificateService from "@/service/certificate/certificate.service.js";

export default {
  onLoad(opt) {
    const location = opt.curLocation.split(",");
    this.curCords = new AMap.LngLat(location[0], location[1]);
  },
  mixins: [AMapMixin],
  data() {
    return {
      newPosition: {
        lng: "",
        lat: ""
      },
      currPosition: undefined,
      positionPicker: undefined,
      curCords: null,
      curEntityName: "",
      isGate: false,
      isSchool: false,
      isBeyond: false
    };
  },
  computed: {},
  methods: {
    initAmap() {
      this.setMapInstance();
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight - 33 + "px";
      // #ifdef H5-DINGDING || H5-WECHAT
      p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + "px";
      // #endif
      return p;
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + "px";
    },
    getRegeocodeInfo() {
      let tmp = "";
      if (!this.currPosition || !this.currPosition.regeocode) {
        return tmp;
      }
      try {
        const name = this.currPosition.regeocode.aois.length
          ? this.currPosition.regeocode.aois[0].name
          : this.currPosition.regeocode.crosses.length
          ? this.currPosition.regeocode.addressComponent.township + this.currPosition.regeocode.crosses[0].second_name
          : this.currPosition.regeocode.addressComponent.township;
        tmp = this.currPosition.regeocode.addressComponent.province + this.currPosition.regeocode.addressComponent.district;
        tmp += name;
        this.curEntityName = name;
      } catch (e) {
        console.log(e);
      }
      return tmp;
    },
    setMapInstance() {
      if (!this.hasInited) return;
      this.amap = new AMap.Map("container", {
        center: this.curCords,
        showControlButton: true,
        zoom: 18
      });
      const _this = this;
      this.loadPlugin("AMap.ControlBar", function() {
        const controlBar = new AMap.ControlBar({
          position: {
            top: "10px",
            right: "10px"
          }
        });
        _this.amap.addControl(controlBar);
      });
      this.drawDefaultInstance();
    },
    // 绘制地图默认实例 当前位置 & 选址图标
    drawDefaultInstance() {
      const curLocation = new AMap.Marker({
        title: "当前位置",
        icon: new AMap.Icon({
          size: new AMap.Size(20, 30),
          imageSize: new AMap.Size(20, 30),
          image: "static/market/new-location.png" // 大图地址
        }),
        position: this.curCords
      });
      curLocation.setMap(this.amap);
      const _this = this;
      AMapUI.loadUI(["misc/PositionPicker"], function(PositionPicker) {
        AMap.PositionPicker = PositionPicker;
        _this.loadMarkList();
      });
    },
    setNewPosition(pos) {
      this.newPosition.lng = pos.lng + "";
      this.newPosition.lat = pos.lat + "";
    },
    loadMarkList() {
      let self = this;
      self.positionPicker = new AMap.PositionPicker({
        mode: "dragMarker",
        map: self.amap,
        iconStyle: {
          url: require("@/static/certificate/position_picker.png"),
          ancher: [30, 60],
          size: [30, 40]
        }
      });
      self.amap.on("click", function(positionResult) {
        self.positionPicker.start(new AMap.LngLat(positionResult.lnglat.getLng(), positionResult.lnglat.getLat()));
      });
      // 修改选址
      self.positionPicker.on("success", function(positionResult) {
        // 限制200m提示
        self.isBeyond = false;
        const distance = Math.round(self.curCords.distance(positionResult.position));
        if (distance > 200) {
          self.isBeyond = true;
          uni.showToast({
            title: "该中小学、幼儿园距离当前位置超过200米，请重新选址。",
            icon: "none",
            duration: 2000
          });
        }
        self.currPosition = {
          accuracy: 0,
          altitude: 0,
          altitudeAccuracy: null,
          heading: null,
          latitude: positionResult.position.getLat(),
          longitude: positionResult.position.getLng(),
          speed: null,
          detailAddress: positionResult["address"],
          regeocode: positionResult.regeocode
        };
        self.setNewPosition({
          lng: positionResult.position.getLng(),
          lat: positionResult.position.getLat()
        });
      });
      self.positionPicker.on("fail", function(positionResult) {
        console.log("获取点坐标失败");
      });
      if (self.curCords) {
        self.positionPicker.start(self.curCords);
        self.setNewPosition({
          lng: self.curCords.getLng(),
          lat: self.curCords.getLat()
        });
      }
      self.amap.panBy(0, 1);
    },
    // 提交新增的实体
    submitEntity() {
      const _this = this;
      // 限制200m提示
      if (this.isBeyond) {
        uni.showToast({
          title: "该中小学、幼儿园距离当前位置超过200米，请重新选址。",
          icon: "none"
        });
        return;
      }
      uni.showModal({
        title: "提示",
        content: `是否将 ${this.curEntityName} 添加到禁入区？`,
        success: async function(res) {
          if (!res.confirm) return;
          // 调禁入区新增接口维护数据
          const { detailAddress, longitude, latitude } = _this.currPosition;
          const idx = detailAddress.indexOf(_this.curEntityName);
          const address = detailAddress.slice(0, idx);
          const backCache = _this.$storage.get("backCache");
          const uuid = _this.thirtyTwoID();
          const baseParam = {
            prohibitName: _this.curEntityName,
            prohibitClassifyCode: _this.isSchool ? "0102" : "0101",
            prohibitAddr: address,
            isActive: 1,
            ownGridUuid: backCache.gridInfo.gridUuid,
            ownOrgUuid: _this.$store.state.userInfo.user.org.orgUuid,
            prohibitUuid: uuid,
            prohibitDesc: address
          };
          const posParam = {
            editable: true,
            pointCoordinatesJson: `{"type":"Point","coordinates":[[[${longitude},${latitude}]]]}`,
            pointName: _this.curEntityName,
            positionType: _this.isGate ? "3" : "1",
            prohibitUuid: uuid
          };
          _this.$u.loading("保存中...");
          const resAll = await Promise.all([certificateService.saveProhibitInfo(baseParam), certificateService.saveProhibitPositions([posParam])]);
          _this.$u.hideLoading();
          if (!resAll[0].success || !resAll[1].success) return;
          const info = {
            address,
            longitude,
            latitude,
            id: uuid,
            bizUUid: uuid,
            name: _this.curEntityName,
            entityType: _this.isSchool ? "school" : "kindergarten",
            type: _this.isSchool ? "03" : "02",
            show: false
          };
          _this.$u.route({ type: "navigateBack" });
          uni.$emit("addEntity", {
            list: JSON.stringify([info])
          });
        }
      });
    },
    // 生成32位ID
    thirtyTwoID() {
      let len = len || 32;
      let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    }
  }
};
</script>

<style scoped lang="scss">
uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

.page {
  padding: 0;
}

#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}

.tip {
  background-color: #f6f6f6;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  position: relative;
}

.m-market {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  padding: 0 30rpx;
}

.row {
  padding-top: 20rpx;
  position: relative;
  color: #666666;
  .row-value {
    color: #333333;
    font-weight: bold;
  }
  .row-button {
    padding: 0 !important;
    margin-bottom: 20rpx;
  }
  .arrow {
    position: absolute;
    right: 0;
    color: #333333;
  }
  /deep/.u-col {
    padding-bottom: 10rpx !important;
  }
}
/deep/.u-image {
  display: inline-block;
  position: absolute;
  top: 8rpx;
}
.u-size-default {
  font-size: 28rpx;
}
</style>
